package com.attendance.chdingtask.service;

import com.attendance.chdingtask.dao.BaseJPA;
import com.attendance.chdingtask.dao.UserInfoDao;
import com.attendance.chdingtask.model.*;
import com.attendance.chdingtask.utils.common.Page;
import com.attendance.chdingtask.utils.dingApi.DeptHelper;
import com.attendance.chdingtask.utils.dingApi.UserHelper;
import com.auth0.jwt.internal.org.apache.commons.lang3.StringUtils;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiDepartmentGetRequest;
import com.dingtalk.api.response.OapiDepartmentGetResponse;
import com.dingtalk.api.response.OapiV2DepartmentGetResponse;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.google.common.base.Objects;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.taobao.api.ApiException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class UserInfoService extends BaseService<UserInfo,Long>{
    @Autowired
    private JPAQueryFactory queryDslTool;
    @Autowired
    private DeptInfoService deptInfoService;
    @Autowired
    private AuthInfoDaoService authHelper;

    @Autowired
    private UserInfoDao dao;

    @Override
    protected BaseJPA<UserInfo> getDao() {
        return dao;
    }

    /**
     * 钉钉人员数据批量保存
     * @param userIds
     * @param corpId
     * @param accessToken
     * @throws Exception
     */
    public void saveListUser(List<String> userIds,String corpId, String accessToken) throws Exception {
        List<UserInfo> list=new ArrayList<>();
        for(String userId:userIds){
            UserInfo info=dao.findByUserid(userId);
            if(null == info){
                UserInfo userInfo=getCorpUserInfo(userId,accessToken);
                userInfo.setCorpId(corpId);
                list.add(userInfo);
            }
        }
        if(null != list&& list.size()>0){
            saveAll(list);
        }

    }


    private UserInfo getCorpUserInfo(String userId, String accessToken) throws Exception {
        UserInfo userInfo=new UserInfo();
        OapiV2UserGetResponse.UserGetResponse response= UserHelper.getUserInfoDetail(accessToken, userId);
        BeanUtils.copyProperties(response, userInfo);
        if(null != response.getDeptOrderList()&& response.getDeptOrderList().size()>0){
            OapiV2UserGetResponse.DeptOrder deptOrder= response.getDeptOrderList().get(0);
            Long deptId= deptOrder.getDeptId();
            Long order=deptOrder.getOrder();
            userInfo.setOrderNo(deptId*order);
        }
        userInfo.setDepartment(StringUtils.join(response.getDeptIdList(), ","));
        if(null!= response.getDeptIdList()&& response.getDeptIdList().size()>0){
            String deptName=getDeptName(response.getDeptIdList(), accessToken);
            userInfo.setDepartmentName(deptName);
        }
        return userInfo;

    }

    private String getDeptName(List<Long> deptIdList, String accessToken) throws ApiException {
        List<String> deptNames=new ArrayList<>();
        for(int i=0;i<deptIdList.size();i++){
            Long deptId=deptIdList.get(i);
            DeptInfo deptInfo=deptInfoService.findByDingDeptId(deptId);
            if(null != deptInfo){
                if(null != deptInfo.getName()){
                    deptNames.add(deptInfo.getName());
                }
            }else{
                OapiV2DepartmentGetResponse.DeptGetResponse deptGetResponse= DeptHelper.getDeptResponse(deptId,accessToken);
                if(null !=deptGetResponse){
                    deptInfo=new DeptInfo();
                    deptInfo.setDeptId(deptGetResponse.getDeptId());
                    deptInfo.setName(deptGetResponse.getName());
                    if(null !=deptGetResponse.getParentId()){
                        deptInfo.setParentId(deptGetResponse.getParentId());
                    }
                    deptInfo.setDeptOrder(deptGetResponse.getOrder());
                    deptInfoService.save(deptInfo);
                    deptNames.add(deptInfo.getName());
                }
            }
        }

        return deptNames.toString();
    }

    public void findUserByData(UserQryParm vo, Page<UserInfo> page, String corpId) {
        QUserInfo qUserInfo=QUserInfo.userInfo;
        JPAQuery<UserInfo> jpaQuery=queryDslTool.select(qUserInfo).from(qUserInfo);
        if(!isEmpty(vo.getUserName())){
            jpaQuery.where(qUserInfo.name.contains(vo.getUserName()));
        }
        if(!isEmpty(vo.getDeptListId())){
            jpaQuery.where(qUserInfo.departmentName.contains(vo.getDeptListId()));
        }
        jpaQuery.where(qUserInfo.dr.eq(0));

        long count=jpaQuery.fetchCount();
        List<UserInfo> list=jpaQuery.offset((page.getPageCurrent() - 1) * page.getPageSize())
                .limit(page.getPageSize())
                .fetch();
        page.setList(list);
        page.setTotal(count);
    }


    public List<UserInfo> findAllUserIds(String corpId) {
        return dao.findAllByCorpIdAndDr(corpId,0);
    }

    public UserInfo findByUserId(String userid) throws Exception {
        UserInfo info=dao.findByUserid(userid);
        if(null == info){
            AuthInfo authInfo=authHelper.findById(1L);
            String accessToken=this.authHelper.getAccessToken(authInfo);
            return getCorpUserInfo(userid,accessToken);
        }
        return info;
    }


}
